<?php

class MessageRepository extends Repository {
	protected $table = 'message';
	
	public function getChatListForUser($user) {
		$query = 'SELECT * 
			FROM message 
			WHERE deleted = 0 AND hidden = 0 AND (fk_from_user_id = ' . $user['uid'] . ' OR fk_to_user_id = ' . $user['uid'] . ') AND uid = (
				SELECT uid
				FROM message AS help_message
				WHERE help_message.deleted = 0 AND help_message.hidden = 0 AND ((help_message.fk_from_user_id = message.fk_from_user_id
					AND help_message.fk_to_user_id = message.fk_to_user_id)
					OR (help_message.fk_from_user_id = message.fk_to_user_id
					AND help_message.fk_to_user_id = message.fk_from_user_id))
				ORDER BY help_message.crdate
				DESC LIMIT 1)
			ORDER BY message.crdate DESC
			LIMIT ' . (($this->page - 1) * ($this->limit)) . ', ' . $this->limit;
		return DB::fetchAll($query, get_class($this));
	}
	
	public function getCountAllChatListForUser($user) {
		$query = 'SELECT count(*) AS countAll
			FROM message 
			WHERE (fk_from_user_id = ' . $user['uid'] . ' OR fk_to_user_id = ' . $user['uid'] . ') AND uid = (
				SELECT uid
				FROM message AS help_message
				WHERE (help_message.fk_from_user_id = message.fk_from_user_id
					AND help_message.fk_to_user_id = message.fk_to_user_id)
					OR (help_message.fk_from_user_id = message.fk_to_user_id
					AND help_message.fk_to_user_id = message.fk_from_user_id)
				ORDER BY help_message.crdate
				DESC LIMIT 1)';
		$res = DB::fetchFirst($query);
		return intval($res['countAll']);
	}
}	

?>